<template>
  <div>
    <Search :search="search" :reset="reset" class="orderQuery">
      <template v-slot:body >
        <!-- <el-form-item label="套餐ID" prop="package_id">
          <el-input v-model="query.package_id" name="package_id" clearable />
        </el-form-item> -->
        <el-form-item label="代理" prop="creator">
          <el-input v-model="query.creator" name="creator" clearable />
        </el-form-item>
        <!-- <el-form-item label="拦截信息" prop="intercept_msg">
          <el-input v-model="query.intercept_msg" name="intercept_msg" clearable />
        </el-form-item> -->
        <el-form-item label="外部订单号" prop="business_order_no">
          <el-input v-model="query.business_order_no" name="business_order_no" clearable />
        </el-form-item>
        <el-form-item label="订单号" prop="order_no">
          <el-input v-model="query.order_no" name="order_no" clearable />
        </el-form-item>
        <el-form-item label="运营商订单号" prop="api_order_no">
          <el-input v-model="query.api_order_no" name="api_order_no" clearable />
        </el-form-item>
        <el-form-item label="开卡号码" prop="phonenum">
          <el-input v-model="query.phonenum" name="phonenum" clearable />
        </el-form-item>
        <el-form-item label="收货人姓名" prop="contact">
          <el-input v-model="query.contact" name="contact" clearable />
        </el-form-item>
        <el-form-item label="收货人手机号" prop="mobile">
          <el-input v-model="query.mobile" name="mobile" clearable />
        </el-form-item>
        <el-form-item label="身份证姓名" prop="iden_card_name">
          <el-input v-model="query.iden_card_name" name="iden_card_name" clearable />
        </el-form-item>
        <el-form-item label="身份证号码" prop="iden_card_id">
          <el-input v-model="query.iden_card_id" name="iden_card_id" clearable />
        </el-form-item>
        <el-form-item label="快递单号" prop="express_no">
          <el-input v-model="query.express_no" name="express_no" clearable />
        </el-form-item>
        <el-form-item label="快递名称" prop="express_name">
          <el-input v-model="query.express_name" name="express_name" clearable />
        </el-form-item>
        <el-form-item label="开卡信息" prop="open_message">
          <el-input v-model="query.open_message" name="open_message" clearable />
        </el-form-item>
        

        <!-- <el-form-item label="拦截状态" prop="intercept_status">
          <el-select v-model="query.intercept_status" placeholder="请选择">
                <el-option
                  v-for="item in intercept_Status"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
        </el-form-item> -->
        <el-form-item label="订单提单同步状态" prop="api_sync">
          <el-select v-model="query.api_sync" placeholder="请选择">
                <el-option
                  v-for="item in sync_Status"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
        </el-form-item>
        <el-form-item label="开卡状态" prop="open_status">
          <el-select v-model="query.open_status" placeholder="请选择">
                <el-option
                  v-for="item in open_Status"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
        </el-form-item>
        <el-form-item label="发货状态" prop="express_status">
          <el-select v-model="query.express_status" placeholder="请选择">
                <el-option
                  v-for="item in express_Status"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
        </el-form-item>
        <el-form-item label="激活状态" prop="active_status" >
            <el-select v-model="query.active_status" placeholder="请选择">
              <el-option
                v-for="item in active_Status"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="首充状态" prop="first_charge_status" >
            <el-select v-model="query.first_charge_status" placeholder="请选择">
              <el-option
                v-for="item in first_charge_Status"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item label="运营商校验" prop="api_valid" >
            <el-select v-model="query.api_valid" placeholder="请选择">
              <el-option
                v-for="item in valid_Status"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        <!-- <el-form-item label="拦截状态" prop="intercept_status">
          <el-input v-model="query.intercept_status" name="intercept_status" clearable />
        </el-form-item> -->
        <!-- <el-form-item label="套餐ID" prop="id">
          <el-input v-model="query.package_id" name="package_id" clearable />
        </el-form-item> -->
      </template>
    </Search>
    <div class="table-default">
      <div class="pt-5 pl-2">
        <el-button @click="importOrder" >导入</el-button>
        <el-button @click="exportOrder" >导出</el-button>
        <el-button  @click="downloadTemplate">下载导入模板</el-button>
      </div>
      <!-- <Operate :show="open" >
        <template #operate>
            <el-button @click="exportOrder" >导出</el-button>
        </template>
      </Operate> -->
      <el-table :data="tableData" class="mt-3" v-loading="loading" >
        <el-table-column prop="id" label="ID" align="center"  />
        <!-- <el-table-column prop="package_id" label="套餐ID" align="center"  /> -->
        <el-table-column prop="name" label="套餐名称" align="center"  >
          <template #default="scope">
            {{ scope.row.package?.name || '暂无' }}
          </template>
        </el-table-column>
        <el-table-column prop="out_package_id" label="套餐编码" align="center"  >
          <template #default="scope">
            {{ scope.row.package?.out_package_id || '暂无' }}
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="代理" align="center"  />
        <!-- <el-table-column prop="intercept_status" label="拦截状态" align="center" >
          <template #default="scope">
            <div v-if="scope.row.intercept_status == 1" class="redLogoType" >
              拦截
            </div>
            <div v-if="scope.row.intercept_status == 2" class="greenLogoType" >
              未拦截
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="intercept_msg" label="拦截信息" align="center" width="130">
          <template #default="scope">
            {{ scope.row.intercept_msg ? scope.row.intercept_msg : '暂无' }}
          </template>
        </el-table-column> -->
        <el-table-column prop="api_sync" label="订单提单同步状态" align="center" >
          <template #default="scope">
            <div v-if="scope.row.api_sync == 1" class="greenLogoType" >
              已同步
            </div>
            <div v-if="scope.row.api_sync == 2" class="grayLogoType">
              未同步
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="api_valid" label="运营商校验" >
          <template #default="scope">
            <div v-if="scope.row.api_valid == 1" class="greenLogoType">
              已校验
            </div>
            <div v-if="scope.row.api_valid == 2" class="grayLogoType" >
              未校验
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="api_lock" label="同步接口锁定时间" align="center" width="130">
          <template #default="scope">
            {{ scope.row.api_lock ? scope.row.api_lock : '暂无' }}
          </template>
        </el-table-column> -->
        <el-table-column prop="api_order_no" label="运营商订单号" align="center" width="130">
          <template #default="scope">
            {{ scope.row.api_order_no ? scope.row.api_order_no : '暂无' }}
          </template>
        </el-table-column>
        <el-table-column prop="business_order_no" label="外部订单号（各销售平台）" align="center" width="130">
          <template #default="scope">
            {{ scope.row.business_order_no ? scope.row.business_order_no : '暂无' }}
          </template>
        </el-table-column>
        <el-table-column prop="order_no" label="订单号" align="center" width="130"/>
        <el-table-column prop="phonenum" label="开卡号码" align="center" width="130"/>
        <el-table-column prop="contact" label="收货人姓名" align="center" />
        <el-table-column prop="mobile" label="联系电话" align="center" width="130"/>
        <el-table-column prop="iden_card_id" label="身份证号码" align="center" width="130"/>
        <el-table-column prop="iden_card_name" label="身份证姓名" align="center" />
        <el-table-column prop="open_status" label="开卡状态" align="center" >
          <template #default="scope">
            <div v-if="scope.row.open_status == 1" class="grayLogoType">
              待开卡
            </div>
            <div v-if="scope.row.open_status == 2" class="openLogoType_ing">
              开卡中
            </div>
            <div v-if="scope.row.open_status == 3" class="openLogoType_success" >
              开卡成功
            </div>
            <div v-if="scope.row.open_status == 4" class="openLogoType_err">
              开卡失败
            </div>
            <div v-if="scope.row.open_status == 5" class="openLogoType_err" >
              开卡异常
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="open_message" label="开卡信息" align="center" width="200">
          <template #default="scope">
            {{ scope.row.open_message ? scope.row.open_message : '暂无' }}
          </template>
        </el-table-column>
        <el-table-column prop="express_status" label="发货状态" align="center" >
          <template #default="scope">
            <div v-if="scope.row.express_status == 1" class="expressLogoType">
              已发快递
            </div>
            <div v-if="scope.row.express_status == 2" class="grayLogoType" >
              未发货
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="express_no" label="快递单号" align="center" width="130">
          <template #default="scope">
            {{ scope.row.express_no ? scope.row.express_no : '暂无' }}
          </template>
        </el-table-column>
        <el-table-column prop="express_name" label="快递名称" align="center" >
          <template #default="scope">
            {{ scope.row.express_name ? scope.row.express_name : '暂无' }}
          </template>
        </el-table-column>
        <el-table-column prop="express_address" label="收货地址" align="center" width="150"/>
        <el-table-column prop="remark" label="备注" align="center" >
          <template #default="scope">
            {{ scope.row.remark ? scope.row.remark : '暂无' }}
          </template>
        </el-table-column>
        <el-table-column prop="active_status" label="激活状态" align="center" >
          <template #default="scope">
            <div v-if="scope.row.active_status == 1" class="greenLogoType" >
              已激活
            </div>
            <div v-if="scope.row.active_status == 2" class="grayLogoType" >
              未激活
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="active_time" label="激活时间" align="center" width="130">
          <template #default="scope">
            {{ scope.row.active_time ? scope.row.active_time : '暂无' }}
          </template>
        </el-table-column>
        <el-table-column prop="first_charge_status" label="首充状态" align="center" >
          <template #default="scope">
            <div v-if="scope.row.first_charge_status == 1" class="greenLogoType" >
              已充值
            </div>
            <div v-if="scope.row.first_charge_status == 2" class="grayLogoType" >
              待充值
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="first_charge_time" label="首充时间" align="center" width="130">
          <template #default="scope">
            {{ scope.row.first_charge_time ? scope.row.first_charge_time : '暂无' }}
          </template>
        </el-table-column>
        <el-table-column prop="first_charge_amount" label="首充金额" align="center" >
          <template #default="scope">
            {{ scope.row.first_charge_amount ? scope.row.first_charge_amount : '暂无' }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" align="center" width="130"/>
        <el-table-column label="操作" width="250"align="center" fixed="right">
          <template #default="scope">
            <Update @click="open(scope.row.id)" />
            <!-- <Destroy @click="destroy(api, scope.row.id)" /> -->
            
            <Down @click="closes(api, scope.row.id)" />
            <el-button @click="revokes(api, scope.row.id)" type="danger"  size="small">  <el-icon size="15" style="padding-right: 2px;padding-bottom: 1px;"><RemoveFilled /></el-icon> 撤单</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Paginate />
    </div>

    <Dialog v-model="visible" :title="title" destroy-on-close>
      <Create @close="close(reset)" :primary="id" :api="api" />
    </Dialog>
    <Dialog v-model="exportVisible" title="导出订单" destroy-on-close>
      <el-form v-model="importData" label-width="150px" ref="form"  class="pr-4" >
          <el-form-item label="导出筛选开始时间" prop="start_date" >
            <el-date-picker
              v-model="importData.start_date"
              type="datetime"
              placeholder="开始时间"
            />
          </el-form-item>
          <el-form-item label="导出筛选结束时间" prop="end_date" >
            <el-date-picker
              v-model="importData.end_date"
              type="datetime"
              placeholder="结束时间"
            />
          </el-form-item>
          <!-- <el-form-item label="导出方式" prop="type" >
            <el-select v-model="importData.type"  clearable placeholder="请选择">
              <el-option
                v-for="item in interceptType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item label="开卡状态" prop="open_status" >
            <el-select v-model="importData.open_status"  clearable placeholder="请选择">
              <el-option
                v-for="item in open_Status"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="发货状态" prop="express_status" >
            <el-select v-model="importData.express_status"  clearable placeholder="请选择">
              <el-option
                v-for="item in express_Status"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="激活状态" prop="active_status" >
            <el-select v-model="importData.active_status"  clearable placeholder="请选择">
              <el-option  
                v-for="item in active_Status"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="首充状态" prop="first_charge_status" >
            <el-select v-model="importData.first_charge_status"  clearable placeholder="请选择">
              <el-option
                v-for="item in first_charge_Status"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <div class="flex justify-end">
            <el-button type="primary" @click="importSubmit(form)">导出</el-button>
          </div>
      </el-form>
    </Dialog>
    <Dialog v-model="orderDatatVisible" title="导出订单数据" destroy-on-close>
      <div>
        {{ orderData }}
      </div>
    </Dialog>
    <Dialog v-model="importVisible" title="导入" destroy-on-close>
      <!-- "http://catchadmin.test/api/selection/selection/import" -->
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        :action=actionApi
        :auto-upload="false"
        :headers="{ authorization: token, 'Request-from': 'Dashboard' }"
        limit="1"
        @start="handleUploadStart"
        @success="handleUploadSuccess"
        @error="handleUploadError"
      >
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template> 
      </el-upload>
      <div v-if="isInvertSuc == true" @click="loadErr" style="text-decoration: underline; cursor: pointer;">订单导入失败，点击获取失败原因</div>
      <div class="flex justify-end">
            <el-button type="primary" @click="importStar">导入</el-button>
      </div>
    </Dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted , ref } from 'vue'
import Create from './create.vue'
import { useGetList } from '@/composables/curd/useGetList'
import { useDestroy } from '@/composables/curd/useDestroy'
import { useCloses } from '@/composables/curd/useClose'
import { useRevokes } from '@/composables/curd/useRevoke'
// import { useRevoke } from '@/composables/curd/useRev'
import { useOpen } from '@/composables/curd/useOpen'
import { useExcelDownload } from '@/composables/curd/useOrderExcelDownload'
import type { UploadInstance , ElMessage  } from 'element-plus'
 import { RemoveFilled } from '@element-plus/icons-vue'
import Message from '@/support/message'
import { env, getAuthToken } from '@/support/helper'
import http from '@/support/http'
import * as XLSX from 'xlsx';

const api = 'order/order'

const { data, query, search, reset, loading } = useGetList(api)
const { destroy, deleted } = useDestroy()
const { closes } = useCloses()
const { revokes } = useRevokes()
const { open, close, title, visible, id } = useOpen()
const { download } = useExcelDownload()
const exportVisible = ref(false)
const importData = ref<object>({type:'file'})
const interceptType = ref([{ value: 'file', label: '文件' },{value:'data',label:'数据'}])
const open_Status = ref([{ value: 1, label: '待开卡' },{value:2,label:'开卡中'},{ value: 3, label: '开卡成功' },{value:4,label:'开卡失败'},{ value: 5, label: '开卡异常' }])
const express_Status = ref([{ value: 1, label: '已发快递' },{value:2,label:'未发货'}])
const active_Status = ref([{ value: 1, label: '已激活' },{value:2,label:'未激活'}])
const first_charge_Status = ref([{ value: 1, label: '已充值' },{value:2,label:'待充值'}])
const intercept_Status = ref([{ value: 1, label: '拦截' },{value:2,label:'未拦截'}])
const valid_Status =  ref([{ value: 1, label: '已校验' },{value:2,label:'未校验'}])
const sync_Status = ref([{ value: 1, label: '已同步' },{value:2,label:'未同步'}])
const orderData = ref([])
const orderDatatVisible = ref(false)
const exportOrder = () => {
  exportVisible.value = true
}

const actionApi = ref<string>('')
const port = window.location.port;
if(port == '8080'){
  actionApi.value = 'https://5g.ghywkj.com.cn:8080/api/order/order/import'
}else if(port == '8081'){
  actionApi.value = 'https://5g.ghywkj.com.cn:8081/api/order/order/import'
}else if(port == '8082'){
  actionApi.value = 'https://5g.ghywkj.com.cn:8082/api/order/order/import'
}else{
  actionApi.value = 'https://5g.ghywkj.com.cn/api/order/order/import'
}

// 导出
const importSubmit = () => {
  if(importData.value.type == 'data'){
    http.get(api,importData.value).then(res => {
      orderData.value = res.data.data
      orderDatatVisible.value = true
    })
  }else{
    download('/order/order',importData.value)
  }
  
}

// 导入
const importVisible = ref(false)
const importOrder = () => {
  importVisible.value = true
}
const token = ref<string>()
token.value = 'Bearer ' + getAuthToken()
const uploadRef = ref<UploadInstance>()
const importStar = () => {
  uploadRef.value!.submit()
}
const handleUploadStart = () => {
  // importMessage.value = '正在上传文件，请稍候...';
};
const isInvertSuc = ref(false)
const isInvertLink = ref()
const handleUploadSuccess = (response, file, fileList) => {
  console.log(response)
  if(response.code == 10000){
    isInvertSuc.value = false
    Message.success('文件导入成功');
    uploadRef.value!.clearFiles()
    importVisible.value = false
    search()
  }else{
    if(response.code){
      Message.error(response.message);
    }else{
      Message.error(response.message);
      isInvertLink.value = response.failed_file
      isInvertSuc.value = true
    }
  }
 
};
// 下载失败原因
const loadErr = () => {
  window.open(isInvertLink.value)
  uploadRef.value!.clearFiles()
  importVisible.value = false
  isInvertSuc.value = false
}
const handleUploadError = (err) => {
  Message.error('文件导入失败');
};

// 下载导入模板

const writeFileAsync = (workbook, filename, options) => {
    return new Promise((resolve, reject) => {
        try {
            XLSX.writeFile(workbook, filename, options);
            resolve();
        } catch (error) {
            reject(error);
        }
    });
}
const downloadTemplate = async () => {
    // 构造json
    const json = [
        {
          '订单号': '',
          '外部订单号': '',
          '产品ID': '',
          '开卡号码(无可留空)': '',
          '收货地址': '',
          '联系姓名': '',
          '联系电话': '',
          '身份证号': '',
          '身份证姓名': '',
          '备注': '',
          '运营商单号': '',
        }
    ];
 
    // 将json数据转换成excel文件
    const worksheet = XLSX.utils.json_to_sheet(json);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
 
    try {
        // 将excel 文件保存为blob
        const blob = await writeFileAsync(workbook, '模板.xlsx', { bookType: 'xlsx', mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
 
        if (blob instanceof Blob) {
            // 创建下载链接
            const url = window.URL.createObjectURL(blob);
 
            // 创建隐藏的a标签，设置下载链接并触发点击
            const a = document.createElement('a');
            a.href = url;
            a.download = 'excel.template.xlsx';
            document.body.appendChild(a);
            a.click();
 
            // 释放对象url
            window.URL.revokeObjectURL(url);
 
            // 等待5秒后关闭模态框
            setTimeout(() => {
                document.body.removeChild(a);
            }, 5000);
        } else {
            throw new Error('Invalid Blob');
        }
    } catch (error) {
        //console.error('Error creating object URL:', error);
    }
}

// const revokeVisible = ref(false)
// 撤单
// const revoke = (val) => {
//   revokeVisible.value = true
// }

const tableData = computed(() => data.value?.data)

onMounted(() => {
  search()
  deleted(reset)
})
</script>
<style lang="scss"scoped>
.orderQuery{
  .el-form-item{
    width: 250px !important;
  }
}
.redLogoType{
  padding: 3px 0px ;
  background-color: #f43f5e;
  color: #fff;width: 100%;
  height: 40%;
  margin: 0 auto;
  border-radius: 5px;
  font-size: 14px;
  text-align: center;
}
.greenLogoType{
  padding: 3px 0px ;
  background-color: #2B842C;
  color: #fff;width: 100%;
  height: 40%;
  margin: 0 auto;
  border-radius: 5px;
  font-size: 14px;
  text-align: center;
}
.grayLogoType{
  padding: 3px 0px ;
  background-color: #909399;
  color: #fff;
  width: 100%;
  height: 40%;margin: 0 auto;
  border-radius: 5px;
  font-size: 14px;
  text-align: center;
}
.expressLogoType{
  padding: 3px 0px ;
  background-color: #2B842C;
  color: #fff;
  width: 100%;
  height: 40%;
  margin: 0 auto;
  border-radius: 5px;
  font-size: 12px;
  text-align: center;
}
.openLogoType_ing{
  padding: 3px 0px ;
  background-color: #e6a23c;
  color: #fff;
  width: 100%;
  height: 40%;
  margin: 0 auto;
  border-radius: 5px;
  font-size: 14px;
  text-align: center;
}
.openLogoType_success{
  padding: 3px 0px ;
  background-color: #717c11;
  color: #fff;
  width: 100%;
  height: 40%;
  margin: 0 auto;
  border-radius: 5px;
  font-size: 12px;
  text-align: center;
}
.openLogoType_err{
  padding: 3px 0px ;
  background-color: #f43f5e;
  color: #fff;
  width: 100%;
  height: 40%;
  margin: 0 auto;
  border-radius: 5px;
  font-size: 12px;
  text-align: center;
}
</style>
 